(function (appid, key) {
    var jck = window.jck || {};
    var util = window.util || {};
    //初始化
    jck.ajax = function (appid, key) {
        this.init.apply(this, arguments);
    };
    jck.ajax.prototype = {
        //对appid /key 的封装
        init: function () {
            var t = this;
            t.appid = appid;
            t.key = key;
        },
        /*
         * 算法逻辑
         * @（params）传入object 、字符串序列化、object FormData这三种参数，传入的数据格式决定了return的数据格式
         *      1: 参数数据类型的标记（paramsType）：
         *           字符串：1
         *           json对象：2
         *           FormData：3
         *      2: 处理参数成字符串
         *      3:增加md5验签逻辑(时间戳)
         *      4:对加密数据进行排序之前先拼上appid和token，排序完成后最后面拼上 key
         *      5:生成签名
         *      6:拼接随机数和签名，并返回最后的数据。
         * */
        md5: function (params) {
            var t = this;
            if (params === null) return null;
            //处理参数 如果传入的是字符串 则对
            var originalParamStr;
            var resultParam = params;
            var paramsType = 0;
            var paramsTypeStr = params.toString();
            if (typeof params === 'string') paramsType = 1; //string
            if ('[object Object]' === paramsTypeStr) {
                paramsType = 2;
            }
            ; //JSON对象
            if ('[object FormData]' === paramsTypeStr) {
                paramsType = 3
            }
            ; //FormData对象
            //不可处理的参数类型报错
            if (!paramsType) return 'parameterTypeError';

            //处理参数成字符串
            switch (paramsType) {
                case 1 : {
                    originalParamStr = params;
                    break;
                }
                case 2 : {
                    originalParamStr = $.param(params);
                    break;
                }
                case 3 : {
                    var iterator = params.entries();
                    var paramFormStr = '';
                    //递归遍历
                    var recursion_iterator = function (data) {
                        if (data.done === false && !(data.value[1] instanceof File)) { //排除文件类型
                            paramFormStr += (data.value[0] + '=' + data.value[1] + '&');
                        }
                        if (data.done === false) {
                            recursion_iterator(iterator.next());
                        }
                    };
                    recursion_iterator(iterator.next());
                    if (paramFormStr.length > 0) paramFormStr = paramFormStr.substring(0, paramFormStr.length - 1);
                    originalParamStr = paramFormStr;
                    break;
                }
            }

            //1.中文解码 2.加号转换为空格
            originalParamStr = decodeURIComponent(originalParamStr).replace(/\+/g, " ");

            //增加md5验签逻辑
            var paramStr = '';
            var noncestr = new Date().getTime();

            var paramObject = {'noncestr': noncestr};
            var keyArray = ['noncestr'];
            var entryStrArray = originalParamStr.split('&');
            for (var i in entryStrArray) {
                var key = entryStrArray[i].split('=')[0];
                var value = entryStrArray[i].split('=')[1];
                if (key && value !== undefined && value !== '') {
                    keyArray.push(key);
                    paramObject[key] = value;
                }
                keyArray.sort();
            }
            var psArr = [];
            for (var i in keyArray) {
                psArr.push(keyArray[i] + '=' + paramObject[keyArray[i]])
                //paramStr += (keyArray[i] + '=' + paramObject[keyArray[i]] + '&');
            }
            paramStr = psArr.join('&')
            //拼上,appid,token
            paramStr = 'appid=' + t.appid + '&' + (paramStr || "");

            //对加密数据进行排序
            function strToObj(str) {
                var obj;
                str = str.replace(/&/g, "','");
                str = str.replace(/=/g, "':'");
                str = "({'" + str + "'})";
                obj = eval(str);
                return obj;
            }

            paramStr = strToObj(paramStr);
            var kName = [], cParam = {};
            for (var ic in paramStr) {
                kName.push(ic);
            }
            kName.sort();
            for (var j in kName) {
                if (!!paramStr[kName[j]]) cParam[kName[j]] = paramStr[kName[j]];
            }
            paramStr = decodeURIComponent($.param(cParam)).replace(/\+/g, " ");
            // 最后拼上key
            paramStr += '&key=' + t.key;
            //生成签名
            var sign = (CryptoJS.MD5(paramStr).toString()).toLocaleUpperCase();

            //签名完成后移除key参数
            paramStr = paramStr.substring(0, paramStr.lastIndexOf('&'));
            //拼接随机数和签名
            switch (paramsType) {
                case 1 : {
                    resultParam = paramStr + ('&sign=' + sign);
                    break;
                }
                case 2 : {
                    resultParam['noncestr'] = noncestr;
                    resultParam['sign'] = sign;
                    resultParam['appid'] = t.appid;
                    break;
                }
                case 3 : {
                    resultParam.append('noncestr', noncestr);
                    resultParam.append('sign', sign);
                    resultParam.append('appid', t.appid);
                    break;
                }
            }
            return resultParam;
        },
        md52: function (params) {
            var self = this;
            var noncestr = new Date().getTime();
            var parm = '{"appid":"' + this.appid + '","noncestr":"' + noncestr + '","key":"' + this.key + '"}'

            params = params ? JSON.stringify(params) : '';
            console.log(params)

            var paramsStr = parm + params;
            console.log(paramsStr)
            return {
                params: params,
                noncestr: noncestr,
                sign: (CryptoJS.MD5(paramsStr).toString()).toLocaleUpperCase()
            }
        },
        //数据加密且执行请求
        //params, url, successCallBack, errorCallBac
        ajax_md5: function (objk) {
            var t = this;
            //加密返回的会在后面追加appid 和
            objk.params = t.md5(objk.params);
            if ('parameterTypeError' === objk.params || objk.params == false) {
                console.log('MD5签名：参数类型错误')
                return false;
            }
            this.ajax(objk)
        },
        //数据加密且执行请求
        ajax_md52: function (params, url, successCallBack, errorCallBack, type) {
            var t = this;
            // if(!t.token){layer.msg('网络延迟，请稍候请求');return ;}
            params = t.md52(params);
            if ('parameterTypeError' === params || params == false) {
                console.log('MD5签名：参数类型错误')
                return false;
            }
            this.ajax2(params, url, successCallBack, errorCallBack, type)
        },
        //ajax封装
        ajax: function (objk) {
            var t = this;
            var p = encryptRSA.objToRsa(objk.params);
            var ajaxObject = {
                type: objk.type || 'POST',
                url: objk.url,
                data: p,
                dataType: 'json',
                cache: false,
                success: function (result) {
                    t.ajaxIng[objk.url] = null;
                    var result = decryptRSA.rsaToObj(result);
                    if (result.success) {
                        if (objk.successCallBack) {
                            objk.successCallBack(result);
                        }
                    } else {
                        if (objk.errorCallBack) {
                            objk.errorCallBack(result);
                        }
                    }
                },
                error: function (data) {
                    t.ajaxIng[objk.url] = null;
                    var d;
                    if (data.status == 200) {
                        //d=t.decrypt.decryptLong(decodeURIComponent(data.responseText).replace(/[\s\n\t]+/g,''));
                        d = decryptRSA.rsaToObj(data.responseText);
                        layer.msg(d.msg || '请求异常，请联系管理员');
                        return;
                    }
                    layer.msg('请求异常，请联系管理员');
                }
            };
            if (!!t.ajaxIng[objk.url]) {
                console.log(objk.url, '数据请求中');
                return;
            }
            t.ajaxIng[objk.url] = $.ajax(ajaxObject);
        },
        //ajax2封装
        ajax2: function (params, url, successCallBack, errorCallBack, type) {
            var t = this;
            var params1 = encryptRSA.objToRsa(params);
            console.log(params1)
            var ajaxObject = {
                type: !type ? 'POST' : type,
                url: url,
                data: params1.params,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    noncestr: params1.noncestr,
                    token: t.token || '',
                    appid: t.appid,
                    sign: params1.sign,
                },
                dataType: 'json',
                cache: false,
                success: function (result) {
                    result = decryptRSA.rsaToObj(result);
                    if (result.success) {
                        if (successCallBack) {
                            successCallBack(result);
                        }
                    } else {
                        if (result.errCode == 10012 && !t.errCode) {
                            t.errCode = true;
                            noConferred(result)
                            return;
                        }
                        if (result.errCode == 10011 && !t.errCode) {
                            t.errCode = true;
                            layer.msg(result.msg, function () {
                                delLocalStorage("yueuserH5")
                                setLocalStorage('ifBindWxUser', "false")
                                delLocalStorage("yueuser")
                                changeUrl('index')
                            })
                            return;
                        }
                        if (errorCallBack) {
                            errorCallBack(result);
                        }
                    }
                },
                error: function (data) {

                    var d;
                    if (data.status == 200 && isRSA) {
                        //d=t.decrypt.decryptLong(decodeURIComponent(data.responseText).replace(/[\s\n\t]+/g,''));
                        d = decryptRSA.rsaToObj(decodeURIComponent(data.responseText).replace(/[\s]+/g, ''));
                        console.log(data.responseText, d);
                        layer.msg(d.msg || '请求异常，请联系管理员');
                        return;
                    }
                    layer.msg('请求异常，请联系管理员');
                }
            };
            $.ajax(ajaxObject);
        },
        //保存请求中的URL
        ajaxIng: {},
        //    时间计算：明后天和上下午计算
        time_count: function (time) {
            var time = time;
            var now = new Date();
            var hour = time.getHours(), hourName = ""
            if (hour < 6) {
                hourName = "凌晨"
            }
            else if (hour < 9) {
                hourName = "早上"
            }
            else if (hour < 12) {
                hourName = "上午"
            }
            else if (hour < 14) {
                hourName = "中午"
            }
            else if (hour < 17) {
                hourName = "下午"
            }
            else if (hour < 19) {
                hourName = "傍晚"
            }
            else if (hour < 22) {
                hourName = "晚上"
            }
            else {
                hourName = "夜晚"
            }
            var dayName = {
                '-2': '前天',
                '-1': '昨天',
                '0': '今天',
                '1': '明天',
                '2': '后天',
            }

            function zeroPoint(dc) {//传入时间戳，返回凌晨时间，用来两个时间相减后计算dayName
                var d = new Date(dc);
                d.setHours(0);
                d.setMinutes(0);
                d.setSeconds(0);
                //时间戳是毫秒级的，所以也需要把时间秒后面的多出来的毫秒给归零
                d = d - d % 1000;
                return d;
            }

            // var dates = Math.abs(Math.floor(((now - time))/(1000*60*60*24)));
            //当前时间减去需要计算的时间。向下四舍五入
            var dates = Math.floor((zeroPoint(time) - zeroPoint(now)) / (1000 * 60 * 60 * 24));

            var dN;
            dN = dayName[dates] || time.format('MM月DD日');
            return {
                day: dN,
                hour: hourName
            }
        },
        //替换{{name}}
        rendering: function (str, obj) {
            if (!obj) {
                return str;
            }
            var html = '', str = str;
            for (var i in obj) {
                var rex = new RegExp('{{' + i + '}}', 'g');
                str = str.replace(rex, obj[i]);
            }
            return str;
        }
    }
    util = {
        localStorage: {
            get: function (key, type) {
                if (window.localStorage) {
                    var storage = window.localStorage;
                    var value;
                    if (type == "object")
                        value = JSON.parse(storage.getItem(key));
                    else
                        value = storage.getItem(key);
                    return value;
                } else {
                    console.error('该应用不支持本地存储！');
                }
            },
            set: function (key, value) {
                if (window.localStorage) {
                    var storage = window.localStorage;
                    if (typeof(value) != "string")
                        storage.setItem(key, JSON.stringify(value));
                    else
                        storage.setItem(key, value);
                } else {
                    console.error('该应用不支持本地存储！');
                }
            },
            del: function () {
                if (window.localStorage) {
                    var storage = window.localStorage;
                    storage.removeItem(key);
                } else {
                    console.error('该应用不支持本地存储！');
                }
            }
        },
        url: {
            getQueryString: function (name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            }
        }
    }
    window.jck = window.jck || {};
    window.jck.ajax = new jck.ajax(appid, key);
    window.util = util;

    /* 图片压缩 */
    /**
     * 初始化数据
     * @param size 需要压缩图片的最小值,只处理大于此数值的。不填默认压缩所有
     * @param quality 图片自定义压缩质量，不填默认50
     */
    var ImgB64 = function (obj) {
        this.size = obj.size > 0 ? obj.size : 0;
        this.quality = obj.quality || 50
    }
    ImgB64.prototype = {
        /**
         * 调用压缩图片
         * @param size 需要压缩图片的最小值,只处理大于此数值的。不填默认压缩所有
         * @param quality 图片自定义压缩质量，不填默认50
         */
        setOption: function (option) {
            if (!option.files) {
                console.log("请选择图片文件");
                return;
            }
            this.option = option;
            this.reader();
        },
        reader: function () {
            var that = this;
            var reader = new FileReader();
            reader.onload = (function () {
                return function (e) {
                    if (that.option.files.size <= that.size) {
                        console.log("不进行压缩")
                        that.option.callback(e.target.result);
                        return;
                    }
                    console.log("进行压缩")
                    that.imgObj(e.target.result);
                }
            })()
            reader.readAsDataURL(that.option.files);
        },
        imgObj: function (baseImg) {
            if (baseImg.indexOf("image/") == -1) {
                alert("请选择图片")
                return;
            }
            var img = new Image(), that = this;
            img.onload = (function () {
                return function (e) {
                    that.canvasObj(this)
                }
            })()
            img.src = baseImg;
        },
        canvasObj: function (imageObj) {
            var mimeType = "image/jpeg", that = this;
            if ((imageObj.src).indexOf("image/png") > -1) {
                mimeType = "image/png";
            }
            var cvs = document.createElement('canvas');
            cvs.width = imageObj.naturalWidth;
            cvs.height = imageObj.naturalHeight;
            var ctx = cvs.getContext("2d").drawImage(imageObj, 0, 0);
            //获取画板图片
            var newImageData = cvs.toDataURL(mimeType, (that.quality) / 100);
            that.option.callback(newImageData)
        }
    }
    window.imgBase64 = new ImgB64({
        size: 1024,//需要压缩得大小KB
        quality: 50
    });

})((appid || ''), 'fffa2a879e62e198924a95dc150dc33823bd0bf7abd3a20fff605f297ae9333804699723a6219048')